﻿namespace Northwind.Web.App
{
    using System.Collections.Generic;
    using System.Linq;
    using NRepository.Core.Query;

    public class NorthwindQueryRepositoryInterceptor : IQueryInterceptor
    {
        private static readonly IEnumerable<IQueryFactory> InterceptorFactories = new IQueryFactory[]
        {
            new AggregateCustomerSalesQueryFactory(),
            new SalesCategoryQueryFactory(),
            new AccountsQueryFactory(),
        };

        public IQueryable<T> Query<T>(
                    IQueryRepository repository,
                    IQueryable<T> query,
                    object additionalQueryData) where T : class
        {
            var factory = InterceptorFactories.FirstOrDefault(p => p.Type == typeof(T));
            if (factory != null)
            {
                var projectedQuery = factory.Query(repository, additionalQueryData);
                return (IQueryable<T>)projectedQuery;
            }

            return query;
        }
    }
}
